package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.acticle.domain.Destination;
import cn.wolfcode.luowowo.acticle.domain.StrategyDetail;
import cn.wolfcode.luowowo.acticle.domain.Travel;
import cn.wolfcode.luowowo.acticle.domain.TravelContent;
import cn.wolfcode.luowowo.acticle.query.TravelQuery;
import cn.wolfcode.luowowo.acticle.service.IDestinationService;
import cn.wolfcode.luowowo.acticle.service.IStrategyDetailService;
import cn.wolfcode.luowowo.acticle.service.ITravelService;
import cn.wolfcode.luowowo.acticle.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.cache.key.RedisKeys;
import cn.wolfcode.luowowo.cache.service.IStrategyRedisService;
import cn.wolfcode.luowowo.cache.service.ITravelRedisService;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelRedisService travelRedisService;
    @Reference
    private IStrategyRedisService strategyRedisService;

    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo")TravelQuery qo){
        model.addAttribute("pageInfo",travelService.query(qo));



        //tcs 最近游记的评论
        TravelCommentQuery query = new TravelCommentQuery();
        Page page = travelCommentService.query(query);
        model.addAttribute("tcs",page.getContent());
        //热门攻略排行 hotCds
        List<StrategyStatisVO> hotVo = strategyRedisService.getAllVo(RedisKeys.STRATEGY_STATIS_HOT_SORT.getPrefix(), 0, 4);
        model.addAttribute("hotCds",hotVo);
        return "travel/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model,Long id,@UserParam UserInfo user){
        //detail
        Travel travel = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        travel.setTravelContent(content);
        model.addAttribute("detail",travel);
        //toasts
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        model.addAttribute("toasts",toasts);
        model.addAttribute("dest",toasts.remove(toasts.size()-1));
        //sds 当前游记目的地下 点击量前三的攻略
        List<StrategyDetail> top3 = strategyDetailService.getViewnumTop3(travel.getDest().getId());
        model.addAttribute("sds",top3);
        //ts 当前游记目的地下 阅读量为前3的游记
        List<Travel> travels = travelService.getViewnumTop3(travel.getDest().getId());
        model.addAttribute("ts",travels);

        //list 评论
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setCurrentPage(1);
        qo.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(qo);
        model.addAttribute("list",page.getContent());


        //编辑按钮的显示
        if(user != null){
            if(travel.getAuthor().getId() == user.getId()){
                model.addAttribute("flag",true);
            }
        }
        //isFavor
        if(user != null){
            boolean flag = travelRedisService.ifFavor(id,user.getId());
            if(flag){
                model.addAttribute("isFavor",flag);
            }
        }

        //vo
        TravelStatisVO vo = travelRedisService.getStatisvo(id);
        model.addAttribute("vo", vo);

        //阅读数+1
        travelRedisService.viewNumIncrease(id, 1);


        return "travel/detail";
    }

    @RequestMapping("/input")
    public String input(Model model,Long id){

        model.addAttribute("dests",destinationService.getDestByDeep(3));

        //tv
        if(id != null){
            Travel travel = travelService.get(id);
            model.addAttribute("tv",travel);
        }

        return "travel/input";
    }
    @RequestMapping("/inputContent")
    @ResponseBody
    public Object inputContent(Model model,Long id){
        TravelContent content = travelService.getContent(id);
        return content;
    }


    //上传图片
    @Value("${file.path}")
    private String filePath;
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    //@RequireLogin
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        //作者
        travel.setAuthor(userInfo);
        Long travelId = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS().addData(travelId);
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment comment,int floor,@UserParam UserInfo user){
        comment.setCity(user.getCity());
        comment.setHeadUrl(user.getHeadImgUrl());
        comment.setLevel(user.getLevel());
        comment.setUserId(user.getId());
        comment.setUsername(user.getNickname());

        TravelComment travelComment = travelCommentService.saveOrUpdate(comment);
        model.addAttribute("c",travelComment);
        //评论数 + 1
        travelRedisService.replyNumIncrease(comment.getTravelId(), 1);
        TravelStatisVO vo = travelRedisService.getStatisvo(comment.getTravelId());


        //floor
        model.addAttribute("floor",floor + 1);
        return "travel/commentTpl";
    }

    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long sid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "请先进行登录");
            result.setCode(102);
            return result;
        }


        boolean ret = travelRedisService.favor(sid, userInfo.getId());

        return new AjaxResult(ret, "").addData(travelRedisService.getStatisvo(sid));
    }

    @RequestMapping("/share")
    @ResponseBody
    public Object share(Long sid) {
        travelRedisService.shareNumIncrease(sid,1);
        return AjaxResult.SUCCESS().addData(travelRedisService.getStatisvo(sid).getSharenum());
    }

    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long sid,@UserParam UserInfo userInfo) {
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false,"请先进行登录");
            result.setCode(102);
            return result;
        }

        boolean ret = travelRedisService.thumbup(sid, userInfo.getId());
        return new AjaxResult(ret, "").addData(travelRedisService.getStatisvo(sid));
    }
}
